package cn.iocoder.yudao.module.reading.service.recommendation;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.reading.controller.app.recommendation.vo.RecommendationZoneRespVO;
import cn.iocoder.yudao.module.reading.convert.recommendation.RecommendationConvert;
import cn.iocoder.yudao.module.reading.dal.dataobject.recommendation.RecommendationZoneDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.recommendation.RecommendationZoneItemDO;
import cn.iocoder.yudao.module.reading.dal.mysql.recommendation.RecommendationZoneItemMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.recommendation.RecommendationZoneMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.RECOMMENDATION_ZONE_NOT_EXISTS;

/**
 * 推荐系统 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class RecommendationServiceImpl implements RecommendationService {

    @Resource
    private RecommendationZoneMapper recommendationZoneMapper;
    
    @Resource
    private RecommendationZoneItemMapper recommendationZoneItemMapper;

    @Override
    public RecommendationZoneDO getRecommendationZone(Long id) {
        return recommendationZoneMapper.selectById(id);
    }

    @Override
    public List<RecommendationZoneRespVO> getRecommendationZones(Long userId, String language, String zoneType) {
        // 查询启用的推荐专区
        List<RecommendationZoneDO> zones = recommendationZoneMapper.selectEnabledZones(language, zoneType);
        
        if (CollUtil.isEmpty(zones)) {
            return new ArrayList<>();
        }
        
        // 转换为响应对象
        List<RecommendationZoneRespVO> result = new ArrayList<>();
        for (RecommendationZoneDO zone : zones) {
            RecommendationZoneRespVO respVO = RecommendationConvert.INSTANCE.convert(zone);
            
            // 获取专区内容（限制数量）
            List<RecommendationZoneItemDO> items = recommendationZoneItemMapper.selectByZoneId(zone.getId(), null, 10);
            respVO.setItems(RecommendationConvert.INSTANCE.convertItemList(items));
            respVO.setItemCount(items.size());
            
            result.add(respVO);
        }
        
        return result;
    }

    @Override
    public RecommendationZoneRespVO getRecommendationZoneDetail(Long userId, Long zoneId, Integer limit) {
        // 校验专区存在
        RecommendationZoneDO zone = recommendationZoneMapper.selectById(zoneId);
        if (zone == null) {
            throw exception(RECOMMENDATION_ZONE_NOT_EXISTS);
        }
        
        // 转换基本信息
        RecommendationZoneRespVO result = RecommendationConvert.INSTANCE.convert(zone);
        
        // 获取专区内容
        List<RecommendationZoneItemDO> items = recommendationZoneItemMapper.selectByZoneId(zoneId, null, limit);
        result.setItems(RecommendationConvert.INSTANCE.convertItemList(items));
        result.setItemCount(items.size());
        
        return result;
    }

    @Override
    public List<RecommendationZoneRespVO> getRecommendationZonesByType(Long userId, String zoneType, String language) {
        return getRecommendationZones(userId, language, zoneType);
    }

    @Override
    public RecommendationZoneRespVO getPersonalizedRecommendations(Long userId, String language, Integer limit) {
        // 简化实现：返回热门推荐专区
        List<RecommendationZoneDO> zones = recommendationZoneMapper.selectEnabledZones(language, "featured");
        
        if (CollUtil.isEmpty(zones)) {
            // 创建空的个性化推荐
            RecommendationZoneRespVO result = new RecommendationZoneRespVO();
            result.setId(0L);
            result.setTitle("个性化推荐");
            result.setDescription("根据您的阅读偏好推荐");
            result.setZoneType("personalized");
            result.setLanguage(language != null ? language : "all");
            result.setItems(new ArrayList<>());
            result.setItemCount(0);
            return result;
        }
        
        // 取第一个专区作为个性化推荐基础
        RecommendationZoneDO zone = zones.get(0);
        RecommendationZoneRespVO result = RecommendationConvert.INSTANCE.convert(zone);
        result.setTitle("个性化推荐");
        result.setZoneType("personalized");
        
        // 获取推荐内容
        List<RecommendationZoneItemDO> items = recommendationZoneItemMapper.selectByZoneId(zone.getId(), null, limit);
        result.setItems(RecommendationConvert.INSTANCE.convertItemList(items));
        result.setItemCount(items.size());
        
        return result;
    }

    @Override
    public List<RecommendationZoneRespVO> getRecommendationsByAge(Long userId, String targetAge, String language) {
        // 简化实现：根据年龄段返回相应的推荐专区
        List<RecommendationZoneDO> zones = recommendationZoneMapper.selectEnabledZones(language, null);
        
        if (CollUtil.isEmpty(zones)) {
            return new ArrayList<>();
        }
        
        // 过滤适合年龄段的专区（简化处理）
        List<RecommendationZoneDO> filteredZones = zones.stream()
                .filter(zone -> isAgeAppropriate(zone, targetAge))
                .collect(Collectors.toList());
        
        // 转换为响应对象
        List<RecommendationZoneRespVO> result = new ArrayList<>();
        for (RecommendationZoneDO zone : filteredZones) {
            RecommendationZoneRespVO respVO = RecommendationConvert.INSTANCE.convert(zone);
            
            // 获取专区内容（限制数量）
            List<RecommendationZoneItemDO> items = recommendationZoneItemMapper.selectByZoneId(zone.getId(), null, 5);
            respVO.setItems(RecommendationConvert.INSTANCE.convertItemList(items));
            respVO.setItemCount(items.size());
            
            result.add(respVO);
        }
        
        return result;
    }
    
    /**
     * 判断专区是否适合指定年龄段（简化实现）
     */
    private boolean isAgeAppropriate(RecommendationZoneDO zone, String targetAge) {
        // 简化处理：如果专区没有年龄限制或者包含目标年龄段，则认为适合
        String zoneAgeRange = zone.getTargetAge();
        if (zoneAgeRange == null || zoneAgeRange.isEmpty()) {
            return true;
        }
        
        // 简单的字符串匹配
        return zoneAgeRange.contains(targetAge) || targetAge.contains(zoneAgeRange);
    }

}
